//
//  NetworkManager.m
//  BBProject
//
//  Created by Evan on 16/5/20.
//  Copyright © 2016年 Evan. All rights reserved.
//

#import "NetworkManager.h"
#import "AFNetworkActivityIndicatorManager.h"
#import "URLHeader.h"
#import "UserCenter.h"


#define   nsErrorStr  @"NSLocalizedDescription"

static NetworkManager *sg_manager = nil;


@interface NetworkManager ()

@end


@implementation NetworkManager

+ (instancetype)sharedManager
{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        //开启转圈圈
        [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
        
        sg_manager = [[NetworkManager alloc] initWithBaseURL:[NSURL URLWithString:YBaseURLString]];
        //超时时间
        sg_manager.requestSerializer.timeoutInterval = 30.f;
        
        // 让AFN支持text/html类型
        sg_manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", @"text/plain",@"application/atom+xml",@"application/xml",@"text/xml",@"application/octet-stream",@"multipart/mixed",@"multipart/form-data", nil];
        
    });
    
    if ([[UserCenter shareCenter] isLogined]) {
        [sg_manager.requestSerializer setValue:[UserCenter shareCenter].authToken forHTTPHeaderField:@"x-api-key"];
        //获取本地ktoken
//        [[NetworkManager sharedManager].requestSerializer valueForHTTPHeaderField:@"x-api-key"];
    }
     [sg_manager.requestSerializer setValue:@"ios" forHTTPHeaderField:@"app-type"];
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    [sg_manager.requestSerializer setValue:app_Version forHTTPHeaderField:@"version"];
    
    return sg_manager;
}



#pragma mark - 网络请求访问的基方法
- (NSURLSessionDataTask *)baseWithUrl:(NSString *)urlString
                           parameters:(NSDictionary *)parameters
                          requestType:(YBMNetworkRequestType )requestType
                            IsLoading:(BOOL )isload
                              success:(success)success
                             failture:(failture)failture
{
    NSLog(@"user Token:%@",[[NetworkManager sharedManager].requestSerializer valueForHTTPHeaderField:@"x-api-key"]);
    urlString = [NSString stringWithFormat:@"%@%@",YBaseURLString,urlString];
    if (requestType == YBMNetworkRequestTypePost) {
        
//        urlString = [NSString stringWithFormat:@"%@%@",YBaseURLString,urlString];
        //        urlString = [NSString stringWithFormat:@"%@?%@",urlString,[self setDictionaryToString:parameters]];
        return  [self POST:urlString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
                 {
                     //错误提示
                     BOOL isCode = [responseObject[@"code"] integerValue] == 200 ? YES : NO;
                     //业务接口字段
                     BOOL isStatus = [responseObject[@"status"] boolValue] ? YES : NO;
                     if(success && isStatus){
                         success(task,responseObject,isCode);
                     }else{
                         //TODO:自定义错误--当业务逻辑失败时，弹出自定义错误
                         NSError *error = [NSError errorWithDomain:NSGlobalDomain code:1000 userInfo:responseObject];
                         NSString *str = [NSString stringWithFormat:@"%@",responseObject[@"message"]];
                         failture(error,str);
                     }
                     
                 } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                     if(failture){
                         NSString *str = [error.userInfo objectForKey:nsErrorStr];
                         failture (error,str);
                         
                     }
                 }];
    }else{
                urlString = [NSString stringWithFormat:@"%@?%@",urlString,[self setDictionaryToString:parameters]];
        return [self GET:urlString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            //错误提示
            BOOL isCode = [responseObject[@"code"] integerValue] == 200 ? YES : NO;
            //业务接口字段
            BOOL isStatus = [responseObject[@"status"] boolValue] ? YES : NO;
            if(success && isStatus){
                success(task,responseObject,isCode);
            }else{
                //TODO:自定义错误--当业务逻辑失败时，弹出自定义错误
                NSError *error = [NSError errorWithDomain:NSGlobalDomain code:1000 userInfo:responseObject];
                NSString *str = [NSString stringWithFormat:@"%@",responseObject[@"message"]];
                failture(error,str);
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if(failture){
                NSString *str = [error.userInfo objectForKey:nsErrorStr];
                failture (error,str);
                
            }
        }];
    }
}

- (NSURLSessionDataTask *)uploadWithUrl:(NSString *)urlString
                             parameters:(NSDictionary *)parameters
                                  image:(UIImage *)image
                                 imgKey:(NSString *)imgKey
                                success:(success)success
                               failture:(failture)failture
{
    NSDictionary *imagesDict = [NSDictionary dictionaryWithObject:image forKey:imgKey];
    
    return [self uploadWithUrl:urlString parameters:parameters imagesDict:imagesDict success:success failture:failture];
}

- (NSURLSessionDataTask *)uploadWithUrl:(NSString *)urlString
                             parameters:(NSDictionary *)parameters
                             imagesDict:(NSDictionary *)imagesDict
                                success:(success)success
                               failture:(failture)failture
{
    return
    [self POST:urlString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData)
     {
         NSArray *imageKeys = [imagesDict allKeys];
         for (NSInteger i= 0; i<imageKeys.count; i++) {
             id obj = [imagesDict objectForKey:imageKeys[i]];
             
             if([obj isKindOfClass:[NSArray class]])
             {
                 NSArray *picArr = (NSArray *)obj;
                 for (int i= 0; i< picArr.count; i++) {
                     
                     [formData appendPartWithFileData:UIImagePNGRepresentation(picArr[i]) name:imageKeys[0] fileName:[NSString stringWithFormat:@"%d.jpg",i] mimeType:@"multipart/form-data"];
                 }
             }
             if([obj isKindOfClass:[UIImage class]])
             {
                 UIImage *image = (UIImage *)obj;
                 [formData appendPartWithFileData:UIImagePNGRepresentation(image)
                                             name:imageKeys[0]
                                         fileName:[NSString stringWithFormat:@"%@.png",imageKeys[0]] mimeType:@"multipart/form-data"]; //application/stream
             }
         }
         
     } progress:^(NSProgress * _Nonnull uploadProgress) {
         
     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         
         if(success){
             success(task,responseObject,YES);
         }
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         if(failture){
             if(failture){
                 NSString *str = [error.userInfo objectForKey:nsErrorStr];
                 failture (error,str);
                 
             }
         }
     }];
}

- (NSString *)setDictionaryToString:(NSDictionary *)dic {
    
    NSString *keyValueFormat;
    NSMutableString *result = [NSMutableString new];
    //实例化一个key枚举器用来存放dictionary的key
    NSEnumerator *keyEnum = [dic keyEnumerator];
    id key;
    while (key = [keyEnum nextObject]) {
        keyValueFormat = [NSString stringWithFormat:@"%@=%@&",key,[dic valueForKey:key]];
        [result appendString:keyValueFormat];
    }
    return [result stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
}

@end
